package com.yiduo.outpost.core.web;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

@Slf4j
public class RestTemplateLoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        traceRequest(request, body);
        ClientHttpResponse response = execution.execute(request, body);
        traceResponse(response);
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) throws IOException {
       StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("-------------请求开始-------------").append("\n");
        stringBuilder.append("URI         : ").append(request.getURI()).append("\n");
        stringBuilder.append("Method      : ").append(request.getMethod()).append("\n");
        stringBuilder.append("Headers     : ").append(request.getHeaders()).append("\n");
        stringBuilder.append("Request body: ").append(new String(body, "UTF-8")).append("\n");
        stringBuilder.append("-------------请求结束-------------").append("\n");
        log.debug(stringBuilder.toString());
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), "UTF-8"));
        String line = bufferedReader.readLine();
        while (line != null) {
            inputStringBuilder.append(line);
            line = bufferedReader.readLine();
        }
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("-------------应答开始-------------").append("\n");
        stringBuilder.append("Status code  : ").append(response.getStatusCode()).append("\n");
        stringBuilder.append("Status text  : ").append(response.getStatusText()).append("\n");
        stringBuilder.append("Headers      : ").append(response.getHeaders()).append("\n");
        stringBuilder.append("Response body: ").append(inputStringBuilder.toString()).append("\n");
        stringBuilder.append("-------------应答结束-------------").append("\n");
        log.debug(stringBuilder.toString());
    }
}
